<template>
  <div class="statistics-container">
    <el-card class="statistics-card">
      <template #header>
        <div class="card-header">
          <span>统计分析</span>
          <div class="header-actions">
            <el-select v-model="timeRange" placeholder="时间范围" @change="handleTimeRangeChange">
              <el-option label="最近24小时" value="24h"></el-option>
              <el-option label="最近7天" value="7d"></el-option>
              <el-option label="最近30天" value="30d"></el-option>
              <el-option label="自定义" value="custom"></el-option>
            </el-select>
            <el-date-picker
              v-if="timeRange === 'custom'"
              v-model="customDateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 240px;"
              @change="handleCustomDateRangeChange"
            />
            <el-button type="primary" size="small" @click="exportData">
              <el-icon><Download /></el-icon> 导出数据
            </el-button>
          </div>
        </div>
      </template>

      <!-- 统计卡片 -->
      <div class="stats-cards">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-number">{{ totalAlerts }}</div>
            <div class="stat-label">总告警数</div>
          </div>
          <div class="stat-icon warning">
            <el-icon><WarningFilled /></el-icon>
          </div>
        </el-card>
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-number">{{ totalVehicles }}</div>
            <div class="stat-label">车辆总数</div>
          </div>
          <div class="stat-icon info">
            <el-icon><Car /></el-icon>
          </div>
        </el-card>
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-number">{{ averageFlowRate }}</div>
            <div class="stat-label">平均车流量(辆/小时)</div>
          </div>
          <div class="stat-icon success">
            <el-icon><TrendCharts /></el-icon>
          </div>
        </el-card>
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-number">{{ peakFlowRate }}</div>
            <div class="stat-label">峰值车流量(辆/小时)</div>
          </div>
          <div class="stat-icon danger">
            <el-icon><Top /></el-icon>
          </div>
        </el-card>
      </div>

      <!-- 图表区域 -->
      <div class="charts-container">
        <!-- 告警趋势图 -->
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>告警趋势</span>
              <el-select v-model="alertChartType" placeholder="图表类型" size="small">
                <el-option label="折线图" value="line"></el-option>
                <el-option label="柱状图" value="bar"></el-option>
              </el-select>
            </div>
          </template>
          <div ref="alertTrendChart" class="chart"></div>
        </el-card>

        <!-- 违规类型分布 -->
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>违规类型分布</span>
              <el-select v-model="violationChartType" placeholder="图表类型" size="small">
                <el-option label="饼图" value="pie"></el-option>
                <el-option label="环形图" value="doughnut"></el-option>
              </el-select>
            </div>
          </template>
          <div ref="violationTypeChart" class="chart"></div>
        </el-card>

        <!-- 车流量趋势 -->
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>车流量趋势</span>
              <el-select v-model="cameraFilter" placeholder="摄像头" size="small" clearable>
                <el-option label="全部" value=""></el-option>
                <el-option v-for="camera in cameras" :key="camera.id" :label="camera.name" :value="camera.id"></el-option>
              </el-select>
            </div>
          </template>
          <div ref="trafficFlowChart" class="chart"></div>
        </el-card>

        <!-- 时段分布 -->
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>时段告警分布</span>
            </div>
          </template>
          <div ref="timeDistributionChart" class="chart"></div>
        </el-card>
      </div>

      <!-- 详细统计表格 -->
      <el-card class="table-card">
        <template #header>
          <div class="chart-header">
            <span>详细统计数据</span>
          </div>
        </template>
        <el-table
          :data="detailedStats"
          style="width: 100%"
          border
        >
          <el-table-column prop="camera_id" label="摄像头ID" width="100" align="center"></el-table-column>
          <el-table-column prop="camera_name" label="摄像头名称" width="150"></el-table-column>
          <el-table-column prop="total_alerts" label="告警总数" width="100" align="center"></el-table-column>
          <el-table-column prop="red_light" label="闯红灯" width="100" align="center"></el-table-column>
          <el-table-column prop="wrong_way" label="逆行" width="100" align="center"></el-table-column>
          <el-table-column prop="speeding" label="超速" width="100" align="center"></el-table-column>
          <el-table-column prop="illegal_parking" label="违停" width="100" align="center"></el-table-column>
          <el-table-column prop="vehicle_count" label="车辆总数" width="100" align="center"></el-table-column>
          <el-table-column prop="flow_rate" label="平均流量" width="100" align="center"></el-table-column>
        </el-table>
      </el-card>
    </el-card>
  </div>
</template>

<script>
import { ref, onMounted, nextTick, watch } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { Download, Warning, Van, DocumentChecked, Top } from '@element-plus/icons-vue'
import { api } from '../api/apiService'

export default {
  name: 'Statistics',
  components: {
      Download,
      Warning,
      Car: Van,
      TrendCharts: DocumentChecked,
      Top
    },
  setup() {
    // 状态
    const alertTrendChart = ref(null)
    const violationTypeChart = ref(null)
    const trafficFlowChart = ref(null)
    const timeDistributionChart = ref(null)
    
    // 筛选条件
    const timeRange = ref('7d')
    const customDateRange = ref([])
    const alertChartType = ref('line')
    const violationChartType = ref('pie')
    const cameraFilter = ref('')
    
    // 统计数据
    const totalAlerts = ref(0)
    const totalVehicles = ref(0)
    const averageFlowRate = ref(0)
    const peakFlowRate = ref(0)
    const cameras = ref([])
    const detailedStats = ref([])
    
    // 图表实例
    let alertChart = null
    let violationChart = null
    let trafficChart = null
    let timeChart = null

    // 获取统计数据
    const fetchStatistics = async () => {
      try {
        // 构建请求参数
        const params = timeRange.value === 'custom' && customDateRange.value.length === 2 
          ? { 
              start_time: customDateRange.value[0], 
              end_time: customDateRange.value[1],
              camera_id: cameraFilter.value || undefined 
            }
          : { 
              time_range: timeRange.value,
              camera_id: cameraFilter.value || undefined 
            };
        
        const response = await api.statistics.getStatistics(params)
        if (response && response.data) {
          updateStatistics(response.data)
          ElMessage.success('数据加载成功')
        } else {
          throw new Error('无效的数据响应')
        }
      } catch (error) {
        console.error('获取统计数据失败:', error)
        ElMessage.warning('获取统计数据失败，使用模拟数据')
        const mockData = generateMockStatistics()
        updateStatistics(mockData)
      }
    }

    // 获取摄像头列表
    const fetchCameras = async () => {
      try {
        const response = await api.cameras.getCameras()
        cameras.value = response.data || []
      } catch (error) {
        // 使用模拟摄像头数据
        cameras.value = [
          { id: 1, name: '东门摄像头' },
          { id: 2, name: '南门摄像头' },
          { id: 3, name: '十字路口摄像头' },
          { id: 4, name: '高速入口摄像头' }
        ]
      }
    }

    // 生成模拟统计数据
    const generateMockStatistics = () => {
      // 生成日期数组
      const generateDates = (days) => {
        const dates = []
        for (let i = days - 1; i >= 0; i--) {
          const date = new Date()
          date.setDate(date.getDate() - i)
          dates.push(date.toLocaleDateString('zh-CN').replace(/\//g, '-'))
        }
        return dates
      }

      // 生成小时数据
      const generateHours = () => {
        return Array.from({ length: 24 }, (_, i) => `${i}:00`)
      }

      const dates = timeRange.value === '24h' ? generateHours() : generateDates(timeRange.value === '7d' ? 7 : 30)
      const cameras = [
        { id: 1, name: '东门摄像头' },
        { id: 2, name: '南门摄像头' },
        { id: 3, name: '十字路口摄像头' },
        { id: 4, name: '高速入口摄像头' }
      ]

      // 告警趋势数据
      const alertTrendData = dates.map(() => Math.floor(Math.random() * 50) + 10)
      
      // 违规类型数据
      const violationTypeData = [
        { name: '闯红灯', value: Math.floor(Math.random() * 300) + 100 },
        { name: '逆行', value: Math.floor(Math.random() * 200) + 50 },
        { name: '超速', value: Math.floor(Math.random() * 250) + 80 },
        { name: '违停', value: Math.floor(Math.random() * 150) + 30 }
      ]

      // 车流量数据
      const trafficFlowData = dates.map(() => Math.floor(Math.random() * 200) + 50)
      
      // 时段分布数据
      const timeDistributionData = Array.from({ length: 24 }, () => Math.floor(Math.random() * 50) + 5)
      
      // 详细统计数据
      const detailedStatsData = cameras.map(camera => {
        const red_light = Math.floor(Math.random() * 50) + 10
        const wrong_way = Math.floor(Math.random() * 30) + 5
        const speeding = Math.floor(Math.random() * 40) + 8
        const illegal_parking = Math.floor(Math.random() * 20) + 3
        const total_alerts = red_light + wrong_way + speeding + illegal_parking
        const vehicle_count = Math.floor(Math.random() * 1000) + 500
        const flow_rate = Math.floor(Math.random() * 50) + 20
        
        return {
          camera_id: camera.id,
          camera_name: camera.name,
          total_alerts,
          red_light,
          wrong_way,
          speeding,
          illegal_parking,
          vehicle_count,
          flow_rate
        }
      })

      // 计算总计
      const totalAlertsSum = detailedStatsData.reduce((sum, item) => sum + item.total_alerts, 0)
      const totalVehiclesSum = detailedStatsData.reduce((sum, item) => sum + item.vehicle_count, 0)
      const avgFlowRate = detailedStatsData.reduce((sum, item) => sum + item.flow_rate, 0) / detailedStatsData.length
      const peakFlowRateVal = Math.max(...detailedStatsData.map(item => item.flow_rate))

      return {
        dates,
        alertTrendData,
        violationTypeData,
        trafficFlowData,
        timeDistributionData,
        detailedStats: detailedStatsData,
        totalAlerts: totalAlertsSum,
        totalVehicles: totalVehiclesSum,
        averageFlowRate: Math.round(avgFlowRate),
        peakFlowRate: peakFlowRateVal
      }
    }

    // 更新统计数据
    const updateStatistics = (data) => {
      totalAlerts.value = data.totalAlerts
      totalVehicles.value = data.totalVehicles
      averageFlowRate.value = data.averageFlowRate
      peakFlowRate.value = data.peakFlowRate
      detailedStats.value = data.detailedStats || []
      
      // 更新图表
      nextTick(() => {
        renderAlertTrendChart(data.dates, data.alertTrendData)
        renderViolationTypeChart(data.violationTypeData)
        renderTrafficFlowChart(data.dates, data.trafficFlowData)
        renderTimeDistributionChart(data.timeDistributionData)
      })
    }

    // 渲染告警趋势图
    const renderAlertTrendChart = (dates, data) => {
      if (!alertTrendChart.value) return
      
      if (alertChart) {
        alertChart.dispose()
      }
      
      alertChart = echarts.init(alertTrendChart.value)
      
      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            return `${params[0].name}<br/>告警数: ${params[0].value}`
          }
        },
        xAxis: {
          type: 'category',
          data: dates,
          axisLabel: {
            rotate: timeRange.value === '30d' ? 45 : 0,
            interval: timeRange.value === '30d' ? 6 : 0
          }
        },
        yAxis: {
          type: 'value',
          name: '告警数'
        },
        series: [{
          data: data,
          type: alertChartType.value,
          smooth: true,
          itemStyle: {
            color: '#f56c6c'
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: 'rgba(245, 108, 108, 0.3)'
              },
              {
                offset: 1,
                color: 'rgba(245, 108, 108, 0.1)'
              }
            ])
          }
        }]
      }
      
      alertChart.setOption(option)
    }

    // 渲染违规类型分布图
    const renderViolationTypeChart = (data) => {
      if (!violationTypeChart.value) return
      
      if (violationChart) {
        violationChart.dispose()
      }
      
      violationChart = echarts.init(violationTypeChart.value)
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'horizontal',
          bottom: 10
        },
        series: [{
          name: '违规类型',
          type: 'pie',
          radius: violationChartType.value === 'pie' ? '65%' : ['40%', '70%'],
          center: ['50%', '45%'],
          data: data,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          itemStyle: {
            borderRadius: 8,
            borderColor: '#fff',
            borderWidth: 2
          }
        }]
      }
      
      violationChart.setOption(option)
    }

    // 渲染车流量趋势图
    const renderTrafficFlowChart = (dates, data) => {
      if (!trafficFlowChart.value) return
      
      if (trafficChart) {
        trafficChart.dispose()
      }
      
      trafficChart = echarts.init(trafficFlowChart.value)
      
      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            return `${params[0].name}<br/>车流量: ${params[0].value}`
          }
        },
        xAxis: {
          type: 'category',
          data: dates,
          axisLabel: {
            rotate: timeRange.value === '30d' ? 45 : 0,
            interval: timeRange.value === '30d' ? 6 : 0
          }
        },
        yAxis: {
          type: 'value',
          name: '车辆数'
        },
        series: [{
          data: data,
          type: 'line',
          smooth: true,
          itemStyle: {
            color: '#409eff'
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: 'rgba(64, 158, 255, 0.3)'
              },
              {
                offset: 1,
                color: 'rgba(64, 158, 255, 0.1)'
              }
            ])
          }
        }]
      }
      
      trafficChart.setOption(option)
    }

    // 渲染时段分布图
    const renderTimeDistributionChart = (data) => {
      if (!timeDistributionChart.value) return
      
      if (timeChart) {
        timeChart.dispose()
      }
      
      timeChart = echarts.init(timeDistributionChart.value)
      
      const hours = Array.from({ length: 24 }, (_, i) => `${i}:00`)
      
      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            return `${params[0].name}<br/>告警数: ${params[0].value}`
          }
        },
        xAxis: {
          type: 'category',
          data: hours,
          axisLabel: {
            interval: 2
          }
        },
        yAxis: {
          type: 'value',
          name: '告警数'
        },
        series: [{
          data: data,
          type: 'bar',
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: '#67c23a'
              },
              {
                offset: 1,
                color: '#85ce61'
              }
            ])
          },
          barWidth: '60%'
        }]
      }
      
      timeChart.setOption(option)
    }

    // 处理时间范围变化
    const handleTimeRangeChange = () => {
      if (timeRange.value !== 'custom') {
        fetchStatistics()
      }
    }

    // 处理自定义日期范围变化
    const handleCustomDateRangeChange = () => {
      if (customDateRange.value.length === 2) {
        fetchStatistics()
      }
    }

    // 导出数据
    const exportData = async () => {
      try {
        // 构建请求参数
        const params = timeRange.value === 'custom' && customDateRange.value.length === 2 
          ? { 
              start_time: customDateRange.value[0], 
              end_time: customDateRange.value[1],
              camera_id: cameraFilter.value || undefined 
            }
          : { 
              time_range: timeRange.value,
              camera_id: cameraFilter.value || undefined 
            };
            
        const response = await api.statistics.exportData(params, { responseType: 'blob' })
        
        // 处理导出文件
        const url = window.URL.createObjectURL(new Blob([response.data]))
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', `statistics_${new Date().getTime()}.csv`)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        
        ElMessage.success('数据导出成功')
      } catch (error) {
        console.error('导出数据失败:', error)
        ElMessage.error('导出数据失败')
      }
    }

    // 监听图表类型变化
    watch(alertChartType, () => {
      fetchStatistics()
    })

    watch(violationChartType, () => {
      fetchStatistics()
    })

    watch(cameraFilter, () => {
      // 实际项目中可以根据摄像头筛选重新获取数据
      fetchStatistics()
    })

    // 响应式处理
    const handleResize = () => {
      alertChart?.resize()
      violationChart?.resize()
      trafficChart?.resize()
      timeChart?.resize()
    }

    // 初始化
    onMounted(async () => {
      await fetchCameras()
      await fetchStatistics()
      window.addEventListener('resize', handleResize)
    })

    return {
      alertTrendChart,
      violationTypeChart,
      trafficFlowChart,
      timeDistributionChart,
      timeRange,
      customDateRange,
      alertChartType,
      violationChartType,
      cameraFilter,
      totalAlerts,
      totalVehicles,
      averageFlowRate,
      peakFlowRate,
      cameras,
      detailedStats,
      handleTimeRangeChange,
      handleCustomDateRangeChange,
      exportData
    }
  }
}
</script>

<style scoped>
.statistics-container {
  padding: 20px;
}

.statistics-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

/* 统计卡片 */
.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin: 20px 0;
}

.stat-card {
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.stat-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  margin-top: 8px;
}

.stat-icon {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  opacity: 0.2;
}

.stat-icon.warning {
  background-color: #e6a23c;
}

.stat-icon.info {
  background-color: #909399;
}

.stat-icon.success {
  background-color: #67c23a;
}

.stat-icon.danger {
  background-color: #f56c6c;
}

/* 图表容器 */
.charts-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
  gap: 20px;
  margin: 20px 0;
}

.chart-card {
  height: 350px;
  display: flex;
  flex-direction: column;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart {
  flex: 1;
  min-height: 0;
}

/* 表格样式 */
.table-card {
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stats-cards {
    grid-template-columns: 1fr;
  }
  
  .charts-container {
    grid-template-columns: 1fr;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .header-actions {
    width: 100%;
    flex-wrap: wrap;
  }
}
</style>